package com.sjf.weibos.protocol;


import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;

public class ProtocolUtil {
	
	public static String copy(Object obj) throws IllegalArgumentException,
			SecurityException, InstantiationException, IllegalAccessException,
			InvocationTargetException, NoSuchMethodException {

		Class<?> classType = obj.getClass();
		Object objectCopy = classType.getConstructor(new Class[] {})
				.newInstance(new Object[] {});
		Field[] fields = classType.getDeclaredFields();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < fields.length; i++) {
			Field field = fields[i];
			String fieldName = field.getName();
			if (fieldName.equals("serialVersionUID")) {
				continue;
			}
			String stringLetter = fieldName.substring(0, 1).toUpperCase();
			String getName = "get" + stringLetter + fieldName.substring(1);
			String setName = "set" + stringLetter + fieldName.substring(1);

			Method getMethod = classType.getMethod(getName, new Class[] {});
			Method setMethod = classType.getMethod(setName,
					new Class[] { field.getType() });
			Object value = getMethod.invoke(obj, new Object[] {});
			if(value!=null){
			sb.append( fieldName + "=" +  value+"&");
			setMethod.invoke(objectCopy, new Object[] { value });}
		}
		return sb.substring(0, sb.length()-1);
	}
	
	public static Object getMapObject(HashMap<String, String> hashMap,Class<?> cls){
		  Object o = null;
			 try { 
				 	o = cls.newInstance();
					Field[] fields = cls.getDeclaredFields();
					for (int j = 0; j < fields.length; j++) {
						Field field = fields[j];
						String fieldName = field.getName();
						Method method = null;
					
						if (fieldName.equals("serialVersionUID")) {
							continue;
						}
						String stringLetter = fieldName.substring(0, 1).toUpperCase();
						String setName = "set" + stringLetter + fieldName.substring(1);
						method = cls.getMethod(setName,
								new Class[] { field.getType() });
						Object value = hashMap.get(fieldName);
						if(value!=null){
						if(hashMap.containsKey(fieldName)){
						    method.invoke(o,value.toString());
						}else{
							method.invoke(o,value.toString()); 
						}
						}
					}
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		return o;
		
	}
}
